package com.ruoyi.web.core.filter;

import com.eic.framework.core.security.SecurityLoginService;
import com.eic.framework.security.LoginJwtHandler;
import com.eic.framework.thread.ThreadPools;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.model.AdminLoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.dao.SysLogininfor;
import com.ruoyi.system.service.ISysLogininforService;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.stereotype.Service;

@Service
public class SecurityLoginServiceImpl implements SecurityLoginService {
    @Override
    public LoginUser createLoginUser(LoginJwtHandler jwt) {
        AdminLoginUser loginUser = new AdminLoginUser();
        loginUser.setJwt(jwt);
        return loginUser;
    }

    @Override
    public void recordLoginInfor(String username, String status, String message) {
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        final String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        ThreadPools.execute(new Runnable() {
            @Override
            public void run() {
                // 打印信息到日志
                logger.info("ip:{},name:{},status:{},message:{}",ip,username,status,message);
                // 获取客户端操作系统
                String os = userAgent.getOperatingSystem().getName();
                // 获取客户端浏览器
                String browser = userAgent.getBrowser().getName();
                // 封装对象
                SysLogininfor logininfor = new SysLogininfor();
                logininfor.setUserName(username);
                logininfor.setIpaddr(ip);
                logininfor.setBrowser(browser);
                logininfor.setOs(os);
                logininfor.setMsg(message);
                // 日志状态
                if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER)) {
                    logininfor.setStatus(Constants.SUCCESS);
                } else if (Constants.LOGIN_FAIL.equals(status)) {
                    logininfor.setStatus(Constants.FAIL);
                }
                // 插入数据
                SpringUtils.getBean(ISysLogininforService.class).insertLogininfor(logininfor);
            }
        });
    }
}
